/*
 *      Created on: March 9, 2011
 *      Author: topcoder
 */
#include <Unit.h>
#include <sstream>

Unit* Unit::unitList_m[INVALIDTYPE] = {NULL, NULL};

Unit::Unit(unsigned int ratio, UnitType type, string name):ratio_m(ratio),type_m(type),name_m(name),nextUnit_m(NULL)
{
    Unit* currentUnit = Unit::unitList_m[type];
    Unit* previousUnit = currentUnit;

    if(currentUnit == NULL)
    {
        unitList_m[type] = this;
    }
    else
    {
        while(currentUnit)
        {
	    if(currentUnit->ratio_m < ratio)
	    {
	        this->nextUnit_m = currentUnit;
	        break;
	    }
	    previousUnit = currentUnit;
	    currentUnit = currentUnit->nextUnit_m;
        }
        previousUnit->nextUnit_m = this;
    }
}
Unit::~Unit()
{
    Unit* currentUnit = Unit::unitList_m[type_m];
    Unit* previousUnit = currentUnit;

    while(this != currentUnit && currentUnit)
    {
        previousUnit = currentUnit;
        currentUnit  = currentUnit->nextUnit_m;
    }

    previousUnit->nextUnit_m = this->nextUnit_m;
}

ostream Unit::print(unsigned long quantity, UnitType type)
{
    Unit* currentUnit = Unit::unitList_m[type];
    unsigned long tempValue = 0;
    ostream tempString;

    while(currentUnit && (quantity != 0))
    {
        if(tempValue = quantity/currentUnit->getRatio())
        {
            tempString << " " << tempValue << " " << currentUnit->getName();
            quantity %= (currentUnit->getRatio());
        }
        currentUnit = currentUnit->nextUnit_m;
    }
    return tempString.str();
}

unsigned int Unit::getRatio()const {return ratio_m;}
UnitType     Unit::getType()const  {return type_m;}
string       Unit::getName()const  {return name_m;}

